﻿using MangoMes.Commont.DTOs.ProductDTOs;
using MangoMes.Commont.DTOs;
using MediatR;
using MangoMes.Commont.Infrastructures.Interfaces;
using MangoMes.Commont.DapperHelps;

namespace ManagoMes.Read.API.Applications.ProductionWorkOrders
{
    public class InspectedListHander : IRequestHandler<InspectedListCommand, CodePageDTO<InspectedListDTO>>
    {
        private readonly IBateRepository<InspectedListDTO> inspect;

        public InspectedListHander(IBateRepository<InspectedListDTO> inspect)
        {
            this.inspect = inspect;
        }

        public async Task<CodePageDTO<InspectedListDTO>> Handle(InspectedListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                CodePageDTO<InspectedListDTO> res = new CodePageDTO<InspectedListDTO>() { Code = 0 };
                DapperHelper dapper = new DapperHelper();
                string sql = @"SELECT a.ToBeInspectedId,a.ToBeInspectedNo,a.SigningNo,c.ProductsNo,d.productManageName,a.Address,a.ToBeInspectedType,a.ToBeInspectedNumber FROM tobeinspected a 
                               JOIN  productionwork b on a.SigningNo=b.ProductionWorkNo 
                               JOIN  productionworkorders c ON b.ProductionWorkOrdersID=c.ProductionWorkOrdersID 
                               JOIN productmanage d on c.ProductsNo=d.productManageNode";
                var list = inspect.GetAll(sql,new InspectedListDTO(),dapper.MangoMesRead).ToList();
                if (!string.IsNullOrEmpty(request.SigningNo))
                {
                    list=list.Where(x=>x.SigningNo.Contains(request.SigningNo)).ToList();
                }
                if (!string.IsNullOrEmpty(request.ProName))
                {
                    list = list.Where(x => x.productManageName.Contains(request.ProName)).ToList();
                }
                if (!string.IsNullOrEmpty(request.ToBeInspectedType))
                {
                    list = list.Where(x => x.ToBeInspectedType.Contains(request.ToBeInspectedType)).ToList();
                }
                res.TotalCount = list.Count;
                res.PageCount = (int)Math.Ceiling(list.Count*1.0/request.pageSize);
                res.Data=list.OrderBy(x=>x.SigningNo).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
